<template>
  <div>
    <Card title="关联商品" :bordered="false" dis-hover class="ivu-mt qw-form-card">
      <Form :model="formData"
            :label-width="140"
            label-position="right"
      >
        <Row :gutter="24"
             type="flex"
        >
          <Col v-bind="grid">
            <FormItem label="商品分类:">
              <Input v-model="formData.classifyInput" readonly @on-search='onSearchClassifyFun' search enter-button
                     placeholder="请选择商品分类"/>
            </FormItem>
          </Col>
          <Col v-bind="grid">
            <FormItem label="SPU编码:">
              <Input v-model="formData.spuNumInput" placeholder="请输入SPU码"></Input>
            </FormItem>
          </Col>
          <Col v-bind="grid">
            <FormItem label="商品名称:">
              <Input v-model="formData.productNameInput" placeholder="请输入商品名称"></Input>
            </FormItem>
          </Col>
          <Col style=" width:100%;margin-top: 10px;justify-content: flex-end;display: flex;margin-bottom:15px">
            <Button type="primary" @click="searchButton">查询</Button>
            <Button style="margin-left: 8px;" @click="resetButton">清空</Button>
          </Col>
        </Row>
      </Form>
    </Card>
    <Card :bordered="false" dis-hover class="ivu-mt qw-form-card">
      <Row
        type="flex"
        style="justify-content:space-between;margin-bottom: 15px"
      >
        <Col>
          <Button :type="switchButton.unRelationStyle" style="margin-right:8px" @click="unRelationButton">未关联</Button>
          <Button :type="switchButton.relationStyle" @click="relationButton">已关联</Button>
        </Col>
        <Col>
          <Button type="primary" @click="batchRelationlButton" v-if="!switchTabFlag">批量关联</Button>
          <Button type="primary" @click="batchCancelButton" v-if="switchTabFlag">批量取消</Button>
        </Col>
      </Row>
      <Table max-height="430" border ref="selection" :columns="columns" :data="tableDataList"
             @on-selection-change="selectionChange">
        <template slot-scope="{ row, index }" slot="action">
          <Button size="small" @click="tableCancelButton(row)" v-if="switchTabFlag">取消</Button>
          <Button type="success" size="small" @click="tableRelationButton(row)" v-if="!switchTabFlag">关联</Button>
        </template>
      </Table>
      <div class="ivu-mt ivu-text-center">
        <Page :total="totalNum" transfer show-total show-elevator show-sizer :current.sync="nowPage"
              @on-change="pageNowchange"
              @on-page-size-change="handleChangePage" :page-size-opts="[10,30,50,100]"/>
      </div>
      <div class="ivu-mt ivu-text-center" style="padding-bottom: 20px">
        <Button style="margin-right:15px" @click="cancelModal">取消</Button>
        <Button type="primary" @click="sureBtn">确认</Button>
      </div>

    </Card>
    <Modal v-model="onSearchClassifyModal" title="选择分类" width="1000">
      <div>
        <Card dis-hover class="ivu-mt">
          <div class="search">
            <Input search enter-button="搜索" placeholder="请输入要搜索的分类名称" @on-search="searchCatogray"/>
          </div>
          <div class="release">
            您当前的选择是：{{ classifyModal.allPathName }}
          </div>
          <div class="Selectiveclassification">
            <Row :gutter="24">
              <Col v-bind="classifyModal.classifyGrid">
                <div class="qw-classify">
                  <Menu active-name="" width="auto" @on-select="selectFirstMenu">
                    <MenuItem :name="item.nowTime" v-for="(item,index) in menuData1" :key="index">
                      {{ item.categoryName }}
                      <Icon type="ios-arrow-forward"/>
                    </MenuItem>
                  </Menu>
                </div>
              </Col>
              <Col v-bind="classifyModal.classifyGrid">
                <div class="qw-classify">
                  <Menu active-name="" width="auto" @on-select="selectSecondMenu">
                    <MenuItem :name="item.nowTime" v-for="(item,index) in menuData2" :key="index">
                      {{ item.categoryName }}
                      <Icon type="ios-arrow-forward"/>
                    </MenuItem>
                  </Menu>
                </div>
              </Col>
              <Col v-bind="classifyModal.classifyGrid">
                <div class="qw-classify">
                  <Menu active-name="" width="auto" @on-select="selectThirdMenu">
                    <MenuItem :name="item.nowTime" v-for="(item,index) in menuData3" :key="index">
                      {{ item.categoryName }}
                      <Icon type="ios-arrow-forward"/>
                    </MenuItem>
                  </Menu>
                </div>
              </Col>
              <Col v-bind="classifyModal.classifyGrid">
                <div class="qw-classify">
                  <Menu active-name="" width="auto" @on-select="selectFourthMenu">
                    <MenuItem :name="item.nowTime" v-for="(item,index) in menuData4" :key="index">
                      {{ item.categoryName }}
                      <Icon type="ios-arrow-forward"/>
                    </MenuItem>
                  </Menu>
                </div>
              </Col>
            </Row>
          </div>
          <div class="qw-searchresult" v-if="classifyModal.isShowResults">
            <div class="qw-search-title">
              <span class="title">搜索结果如下：</span>
              <Button type="text" icon="md-close" @click="classifyModal.isShowResults = false">关闭</Button>
            </div>
            <div class="qw-search-body">
              <RadioGroup v-if="classifyModal.searchData.length>0" v-model="classifyModal.categoryUuid" vertical
                          @on-change='search(classifyModal.categoryUuid)'>
                <Radio :label="item.categoryUuid" v-for="(item, index) in classifyModal.searchData" :key="index">
                  <span>{{ item.categoryPath }}</span>
                </Radio>
              </RadioGroup>
              <div class="qw-searchno" v-else>未找到相关分类~~</div>
            </div>
          </div>
        </Card>
      </div>
      <div slot="footer" class="ivu-mt ivu-text-center" style="padding-bottom: 20px">
        <Button style="margin-right:15px" @click="cancelClassify">取消</Button>
        <Button type="primary" @click="saveClassifyFun">确认</Button>
      </div>
    </Modal>

  </div>

</template>

<script>
import {ApiRequest} from "@api/basePage";
import {getBtnsId} from "@/libs/btnsPermission";

export default {
  name: "relationProduct",
  data() {
    return {
      totalNum: 0,
      nowPage: 1,
      switchButton: {
        relationStyle: 'default',
        unRelationStyle: 'primary',
      },
      switchTabFlag: false,//切换已关联未关联按钮 false 未关联 true 已关联
      formData: {
        classifyInput: '',
        spuNumInput: '',
        productNameInput: ''
      },
      selectedData: [],
      grid: {
        xl: 8,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24
      },
      columns: [
        {
          type: 'selection',
          width: 60,
          fixed: 'left',
          align: 'center'
        },
        {
          title: '商品分类',
          minWidth: 120,
          key: 'categoryPath',
          align: 'center'
        },
        {
          title: '商品名称',
          minWidth: 120,
          key: 'productName',
          align: 'center'
        },
        {
          title: 'SPU编码',
          minWidth: 120,
          key: 'spuNo',
          align: 'center'
        },
        {
          title: '品牌',
          minWidth: 120,
          key: 'brandName',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 180
        }
      ],
      tableDataList: [],
      onSearchClassifyModal: false,//查询分类的弹框
      menuData1:[], //一级分类
      menuData2:[],//二级分类
      menuData3:[],//三级分类
      menuData4:[],//四级分类
      catograyLevel: '0', // 分类级别
      categoryUuid: '',
      classifyModal: {
        catograyLevel: 0,//分类级别
        allPathName: '', // 分类全路径名称
        classifyGrid: {
          xl: 6,
          lg: 6,
          md: 6,
          sm: 24,
          xs: 24
        },
        isShowResults: false,
        searchData: [],
        categoryUuid: '',
      },
      searchdata: {
        categoryName: '',
        categoryUuid: '',
        templateName: '',
        templateUuid: '',
        spuNo: '',
        productNameFinal: '',
      },
      apiObj: {
        //关联商品 商品信息查询
        getSaleAreaList: {
          url: '/sysback/modifySaleArea/getRelatedSpuList', // 接口地址
          type: 'post'
        },

        // 搜索分类
        getCategoryListByKey: {
          url: '/sysback/choose/category/getCategoryListByKey', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 查询一级分类
        getLevelOneCategoryList: {
          url: '/sysback/choose/category/getLevelOneCategoryList', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 根据父分类查询子分类
        getByParentUuid: {
          url: '/sysback/choose/category/getByParentUuid', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 模板放大镜，弹出模板列表
        getPagerByTemplate: {
          url: '/sysback/batch/add/basicinfo/getPagerByTemplate', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 模板-模糊联想精准搜索
        getByTemplateName: {
          url: '/sysback/batch/add/basicinfo/getByTemplateName', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 查询未关联商品列表
        getProductList: {
          url: '/sysback/update/product/structure/getProductList', // 接口地址
          type: 'post' // 接口请求类型
        },
      },
      nowTime: '',
      handleRelationFlag:false,//接口成功标识
      tableParams: {
        pageShow: 10,//每页条数
        nowPage: 1,//当前页
        categoryUuid: '',//品类uuid
        productName: '',//商品名称
        spuNo: '',//spu编码
      },
      relationUuid:[]
    }
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      let params = {};
      let curBtnId = getBtnsId('关联商品')
      sessionStorage.setItem('buttonId', curBtnId)
      ApiRequest(this.apiObj.getSaleAreaList.url, this.apiObj.getSaleAreaList.type, this.tableParams).then((data) => {
        if (data.retStatus == 1) {
          let result = data.retData.results ? data.retData.results : [];
          this.totalNum = data.retData.totalNum;
          this.tableDataList = result;
          this.handleRelationFlag = true;
        }else{
          this.handleRelationFlag = false;
        }
      })
    },
    // 查询
    searchButton() {
      this.tableParams.productName = this.formData.productNameInput;
      this.tableParams.spuNo = this.formData.spuNumInput;
      this.tableParams.pageShow = 10;
      this.tableParams.nowPage = 1;
      this.tableParams.categoryUuid = this.searchdata.categoryUuid
      this.getData();
    },
    handleChangePage(val) {
      this.tableParams.pageShow = val;
      this.getData();
    },
    // 当前第几页
    pageNowchange(val) {
      this.tableParams.nowPage = val;
      this.getData();
    },
    // 清空
    resetButton() {
      this.formData.classifyInput = '';
      this.formData.spuNumInput = '';
      this.formData.productNameInput = '';
      this.searchdata.categoryUuid = '';
      this.tableDataList = [];
    },
    //批量取消
    batchCancelButton() {
      if (this.selectedData.length <= 0) {
       return  this.$Message.info('请勾选你要取消的数据');
      }
      this.selectedData.forEach((item)=>{
        this.relationUuid.splice(this.relationUuid.indexOf(item.productUuid),1)
      });
      if(this.relationUuid.length > 0){
        this.tableParams.productUuidInList = this.relationUuid;
        this.getData();
      }else{
        this.tableDataList = [];
      }
    },
    // 批量关联
    batchRelationlButton(){
      if (this.selectedData.length <= 0) {
        return this.$Message.info('请勾选你要关联的数据');
      }
      this.selectedData.forEach((item)=>{
          if(this.relationUuid.indexOf(item.productUuid) <=-1){
            this.relationUuid.push(item.productUuid)
          }
      });
      this.tableParams.productUuidNotInList = this.relationUuid;
      this.tableParams.productUuidInList = [];
      this.getData();
    },
    //表格中的取消-删除操作
    tableCancelButton(data) {
       let productUuid = data.productUuid;
       this.relationUuid.splice(this.relationUuid.indexOf(productUuid),1);
       this.tableParams.productUuidInList = this.relationUuid;
       if(this.relationUuid.length > 0){
         this.getData();
       }else{
         this.tableDataList = [];
       }
    },
    // 表格中的关联操作
    tableRelationButton(data) {
      let productUuid = data.productUuid;
      this.relationUuid.push(productUuid)
      this.tableParams.productUuidNotInList =  this.relationUuid;
      this.getData();
      if(this.handleRelationFlag){
        this.$Message.success('关联成功')
      }else{
        this.$Message.success('关联失败')
      }
    },

    //
    selectionChange(data) {
      this.selectedData = data;
    },

    // 已关联
    relationButton() {
      this.switchTabFlag = true;
      this.switchButton.relationStyle = 'primary';
      this.switchButton.unRelationStyle = 'default';
      this.selectedData = [];
      let productUuid = JSON.parse(sessionStorage.getItem('productUuid'));
      if(productUuid){
        productUuid.forEach((item)=>{
            this.relationUuid.push(item)
        })
      }

      if(this.relationUuid.length >0){
        this.tableParams.productUuidInList = [...new Set(this.relationUuid)];
        this.tableParams.productUuidNotInList = [];
        this.getData();
      }else{
        this.tableDataList = [];
      }

    },
    // 未关联
    unRelationButton() {
      this.switchTabFlag = false;
      this.switchButton.relationStyle = 'default';
      this.switchButton.unRelationStyle = 'primary';
      this.tableParams.productUuidInList = [];
      this.tableParams.productUuidNotInList = this.relationUuid;
      this.selectedData = [];
      this.getData();
    },

    // 取消-弹窗按钮
    cancelModal() {
      this.$router.push({
        path: "/commodity/commodityInfoUpdate/modifySalesArea/modifySalesAreaLists"
      })
    },

    // 确认- 弹窗按钮
    sureBtn() {
      this.$router.go(-1);
     /* 修复bug-修改销售区域-关联多个spu后，想取消掉一个，取消失败 */
      let relationUuidAry = [...new Set(this.relationUuid)]
      sessionStorage.setItem('productUuid', JSON.stringify(relationUuidAry))
    },

    // 选择分类的弹窗
    onSearchClassifyFun() {
      this.onSearchClassifyModal = true;
      this.menuData1 = [];
      this.menuData2 = [];
      this.menuData3 = [];
      this.menuData4 = [];
      this.classifyModal.allPathName = '';
      this.classifyModal.isShowResults = false;
      this.getLevelOneCategoryList();
    },
    // 获取分类路径全名称
    getSubCategory(level = this.catograyLevel) {
      this.level = '0'
      let nextLevel = Number(level) + 1;
      let data = {
        parentUuid: this.categoryUuid,
        categoryType: this.productType
      }
      // 开始请求列表
      ApiRequest(this.apiObj.getByParentUuid.url, this.apiObj.getByParentUuid.type, data, true).then(res => {
        if (res.retStatus === '1') {
          if (level === '1') {
            this.menuData2 = [];
            this.menuData3 = [];
            this.menuData4 = [];
          } else if (level === '2') {
            this.menuData3 = [];
            this.menuData4 = [];
          } else if (level === '3') {
            this.menuData4 = [];
          }
          this.level = level
          if (nextLevel <= 5) {
            res.retData.forEach(element => {
              element.nowTime = element.categoryUuid + ',' + this.nowTime;
            });
            this.$data['menuData' + Number(nextLevel)] = res.retData;
            if (res.retData.length === 0) {
              this.lastLevel = true;
            } else {
              this.lastLevel = false;
            }
          }
        }
      })
    },
    // 获取一级目录
    getLevelOneCategoryList(level = this.classifyModal.catograyLevel) {
      this.level = '0'
      let nextLevel = 1;
      let data = {}
      // 开始请求列表
      ApiRequest(this.apiObj.getLevelOneCategoryList.url, this.apiObj.getLevelOneCategoryList.type, data, true).then(res => {
        if (res.retStatus === '1') {
          if (level === '1') {
            this.classifyModal.secondClassify = [];
            this.classifyModal.thirdClassify = [];
            this.classifyModal.fourthClassify = [];
          } else if (level === '2') {
            this.classifyModal.thirdClassify = [];
            this.classifyModal.fourthClassify = [];
          } else if (level === '3') {
            this.classifyModal.fourthClassify = [];
          }
          this.level = level;
          if (nextLevel <= 5) {
            res.retData.forEach(element => {
              element.nowTime = element.categoryUuid + ',' + this.nowTime;
            });
            this.$data['menuData' + Number(nextLevel)] = res.retData;
            if (res.retData.length === 0) {
              this.lastLevel = true;
            } else {
              this.lastLevel = false;
            }
          }
        }
      })
    },
    // 点击分类
    // 选中一级分类
    selectFirstMenu(name) {
      name = name.split(',')[0];
      this.catograyLevel = '1';
      this.categoryUuid = name;
      this.getSubCategory('1');
    },
    // 选中二级分类
    selectSecondMenu(name) {
      name = name.split(',')[0];
      this.catograyLevel = '2';
      this.categoryUuid = name;
      this.getSubCategory('2');
    },
    // 选中三级分类
    selectThirdMenu(name) {
      name = name.split(',')[0];
      this.catograyLevel = '3';
      this.categoryUuid = name;
      this.searchdata.categoryUuid = name;
      this.getSubCategory('3');
    },
    // 选中四级分类
    selectFourthMenu(name) {
      name = name.split(',')[0];
      this.catograyLevel = '4';
      this.categoryUuid = name;
      this.classifyModal.categoryUuid = name;
      this.menuData4.forEach(element => {
        if (element.categoryUuid == name) {
          this.classifyModal.allPathName = element.categoryName;
          this.formData.classifyInput = element.categoryName;
        }
      });
      this.getSubCategory('4');
    },

    // 选完分类进入下一步操作
    saveClassifyFun() {
      if (this.categoryUuid === 'systemUuid') {
        this.$Message.error('请先选择分类')
        return;
      }
      if (!this.lastLevel) {
        this.$Message.error('请选择到最后一级分类')
        return;
      }
      this.searchdata.categoryName = this.classifyModal.allPathName;
      this.searchdata.categoryUuid = this.classifyModal.categoryUuid;
      this.formData.classifyInput = this.classifyModal.allPathName;
      this.onSearchClassifyModal = false;
    },
    // 取消操作
    cancelClassify(){
      this.onSearchClassifyModal = false;
    },

    //  搜索分类
    searchCatogray(value) {
      if (value === '') {
        this.$Message.error('请输入需要搜索的分类名称!');
        return false;
      }
      let data = {
        // key: value,
      }
      let curBtnId = getBtnsId('关联商品')
      sessionStorage.setItem('buttonId', curBtnId)
      // 开始请求列表
      ApiRequest(this.apiObj.getCategoryListByKey.url + '?key=' + value, this.apiObj.getCategoryListByKey.type, data, true).then(res => { // xfs-2021-7-31修改过传参方式
        let resultData = [];
        if (res.retStatus === '1') {
          resultData = res.retData;
        }
        if (!this.classifyModal.isShowResults) {
          this.classifyModal.isShowResults = true;
        }
        this.classifyModal.searchData = resultData;
        this.level = '4'
      })
    },

    search(categoryUuid) {
      this.lastLevel = true
      this.searchdata.categoryUuid = categoryUuid
      this.classifyModal.searchData.forEach(item => {
        if (item.categoryUuid === categoryUuid) {
          this.classifyModal.allPathName = item.categoryPath
          this.searchdata.categoryName = this.allPathName;
        }
      })
      this.level = '4'
    },
  }
}
</script>

<style lang="less" scoped>
.div {
  display: flex;

  > span:nth-of-type(2),
  > span:nth-of-type(3) {
    margin-left: 20px;
  }
}

.a {
  background: #5d8ae3 !important;

  > div {
    border-left: 40px solid #5d8ae3 !important;
  }
}

.b {
  background: #5d8ae3 !important;

  > div:nth-of-type(1) {
    border-left: 40px solid #5d8ae3 !important;
  }

  > div:nth-of-type(2) {
    position: absolute;
    top: 0px;
    left: -20px;
    border-top: 20px solid #5d8ae3 !important;
    border-right: 0px solid #5d8ae3 !important;
    border-bottom: 20px solid #5d8ae3 !important;
  }
}

.release {
  width: 100%;
  height: 40px;
  line-height: 40px;
  background: #fbfafa;
  text-indent: 10px;
  margin-top: 16px;
}

.btn {
  width: 120px;
  margin: 16px 20px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  color: white;
  font-size: 15px;
  border-radius: 4px;
  background: #5d8ae3;
}

.qw-classify {
  height: 300px;
  overflow-y: auto;
  border: 1px solid #eeeeee;

  & /deep/ .ivu-menu {
    z-index: 10;

    &.ivu-menu-vertical.ivu-menu-light:after {
      display: none;
    }

    &.ivu-menu-light.ivu-menu-vertical .ivu-menu-item-active:not(.ivu-menu-submenu):after {
      display: none;
    }

    & > .ivu-menu-item {
      padding: 10px 24px 10px 14px;

      .ivu-icon {
        position: absolute;
        right: 6px;
        top: 14px;
        display: none;
      }
    }

    .ivu-menu-item-active,
    .ivu-menu-item:hover {
      .ivu-icon {
        display: inline-block;
      }
    }
  }
}

.qw-reselect {
  margin-left: 20px;
  color: #95c85a;
  cursor: pointer;
}

.qw-searchresult {
  margin-top: 24px;
  border: 1px solid #eee;

  .qw-search-title {
    display: flex;
    background: #fbfafa;
    justify-items: center;
    align-items: center;
    padding: 0 0 0 10px;

    .title {
      flex: 1;
    }
  }

  .qw-searchno {
    padding: 16px;
  }

  & /deep/ .qw-search-body {
    .ivu-radio-group {
      display: block;

      .ivu-radio-group-item:not(last-child) {
        padding: 0 16px;
        height: 50px;
        line-height: 50px;
        border-bottom: 1px solid #eee;
      }

      .ivu-radio-group-item:hover {
        background-color: #f0f7ff;
      }
    }
  }
}

.search {
  width: 100%;
  padding: 10px 64px;
  background: #eaf7f9;
}
</style>
